<?php

namespace Lavender;


class FLog
{
	const LEVEL_OF_DEBUG = "debug";
	const LEVEL_OF_INFO  = "info";
	const LEVEL_OF_WARN = "warn";
	const LEVEL_OF_ERROR = "error";
	const LEVEL_OF_FATAL = "fatal";

	public static function log($level, $module, $cat, $format, ...$ext)
	{
		$old_mask = umask(0);
		$dir = L_WORKSPACE_PATH . 'log' . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR;
		if (!is_dir($dir)) {
			mkdir($dir, 0777, true);
		}
		$timestr = microtime();
		$time_split = explode(" ", $timestr);
		$timestamp = intval($time_split[1]);
		$ms_second = substr($time_split[0], 2, 6);
		$filename = sprintf("%s_%s.log", empty($cat) ? "log" : $cat, date('Ymd', $timestamp));
		$date_str = date("H:i:s", $timestamp);
		$real_format = sprintf("%s.%s %s %s\n", $date_str, $ms_second, $level, $format);
		if(count($ext) > 0){ //避免太长的sprintf format 消耗
			$content = sprintf($real_format, ...$ext);
		}
		else{
			$content = $real_format;
		}
		$file = $dir . $filename;
		file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
		umask($old_mask);
	}

	public static function getDefaultModule()
	{
		if (defined("L_APP_NAME")) {
			return L_APP_NAME;
		}
		return "runtime";
	}

	public static function debug($cat, $format, ...$ext)
	{
		return self::log(self::LEVEL_OF_DEBUG, self::getDefaultModule(), $cat, $format, ...$ext);
	}

	public static function info($cat, $format, ...$ext)
	{
		return self::log(self::LEVEL_OF_INFO, self::getDefaultModule(), $cat, $format, ...$ext);
	}

	public static function warn($cat, $format, ...$ext)
	{
		return self::log(self::LEVEL_OF_WARN, self::getDefaultModule(), $cat, $format, ...$ext);
	}

	public static function warning($cat, $format, ...$ext)
	{
		return self::warn($cat, $format, ...$ext);
	}

	public static function error($cat, $format, ...$ext)
	{
		return self::log(self::LEVEL_OF_ERROR, self::getDefaultModule(), $cat, $format, ...$ext);
	}

	public static function fatal($cat, $format, ...$ext)
	{
		return self::log(self::LEVEL_OF_FATAL, self::getDefaultModule(), $cat, $format, ...$ext);
	}

	public static function simpleLog($content,$level = self::LEVEL_OF_DEBUG,$cat = ''){
		if(empty($cat)){
			$arr = debug_backtrace();
			if(count($arr) < 2){
				$cat = "log";
			}
			else{
				$cat = basename($arr[1]['class']);
			}
		}
		return self::log($level, self::getDefaultModule(), $cat, $content);
	}
}
